package com.ice_col.guesssongname.ui;

import android.app.Activity;
import android.graphics.Color;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ice_col.guesssongname.R;
import com.ice_col.guesssongname.data.Const;
import com.ice_col.guesssongname.model.SongInformation;
import com.ice_col.guesssongname.util.Util;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity implements WordsGridView.WordSelectListener,SelectedWordsView.SelectedWordClickListener{

    public static final String TAG="MainActivity";

    private SelectedWordsView mSelectedWordView;
    private WordsGridView mWordsView;
    private Button mPlayButton;
    private int mCurrentLevel;
    private int mCurrentCoins;
    private SongInformation mCurrentSong;
    private int[] answer;
    private String[] currentSelectedWords;
    private LinearLayout mPassLevel;
    private ImageButton mNextLevelButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        int record[]=Util.readData(this);
        mCurrentLevel=record[0]+1;
        mCurrentCoins=record[1];
        initView();
        init();
    }

    private void init(){


        //read record

        mCurrentLevel++;
        Log.i(TAG,"read record finish:"+mCurrentLevel+mCurrentCoins);

        //init song's information
        mCurrentSong=new SongInformation();
        mCurrentSong.setFileName(Const.SONG_INFO[mCurrentLevel][0]);
        mCurrentSong.setSongName(Const.SONG_INFO[mCurrentLevel][1]);
        Log.i(TAG, "init song info finish:" + mCurrentSong.getFileName() + "\n" + mCurrentSong.getSongName());

        generateAnswer();

        //init words list & selected words view

        mSelectedWordView.initButton(mCurrentSong.getSongCharacterNum());
        mSelectedWordView.registerWordClickListener(this);
        mWordsView.initWords(answer, mCurrentSong.getSongName());
        mWordsView.registerListener(this);

        //
        currentSelectedWords=new String[mCurrentSong.getSongCharacterNum()];
    }

    private void initView(){
        mSelectedWordView=(SelectedWordsView) findViewById(R.id.word_selected_show);
        mWordsView=(WordsGridView) findViewById(R.id.gridview_words);
        mPassLevel=(LinearLayout) findViewById(R.id.level_pass_view);
        mNextLevelButton=(ImageButton) findViewById(R.id.next_level_button);

        mNextLevelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPassLevel.setVisibility(View.GONE);
                init();
            }
        });
    }

    private void generateAnswer(){
        answer=new int[mCurrentSong.getSongCharacterNum()];
        Random random=new Random();
        for(int i=0;i<mCurrentSong.getSongCharacterNum();i++) {
            int randomIndex = random.nextInt(WordsGridView.WORD_NUM);
            answer[i]=randomIndex;
        }
    }

    @Override
    public void onWordSelected(int position,View view) {
        if(mSelectedWordView.isFinished()){
            Toast.makeText(this, "Fished", Toast.LENGTH_LONG).show();
            if (checkAnswer()) {
                Toast.makeText(this, "Bingo", Toast.LENGTH_LONG).show();
                dealPassCurrentLevel();
            } else {
                Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();
                twinkleWords();
            }
        }else{
            int i=mSelectedWordView.getUnusedButtonIndex();
            Button tButton=mSelectedWordView.getButton(i);
            mSelectedWordView.setMemento(i, position);
            tButton.setText(mWordsView.getWord()[position]);
            mSelectedWordView.setState(i, true);
            TextView textView=(TextView) view.findViewById(R.id.gridview_item_button);
            if(textView.getVisibility()== View.VISIBLE) {
                textView.setVisibility(View.GONE);
            }
            if(mSelectedWordView.isFinished()) {
                Toast.makeText(this, "Fished", Toast.LENGTH_LONG).show();
                if (checkAnswer()) {
                    Toast.makeText(this, "Bingo", Toast.LENGTH_LONG).show();
                    dealPassCurrentLevel();
                } else {
                    Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();
                    twinkleWords();
                }
            }
        }
    }

    private void dealPassCurrentLevel(){
        mPassLevel.setVisibility(View.VISIBLE);
    }

    private void twinkleWords(){
        TimerTask task=new TimerTask() {
            int twinkleTimes=0;
            boolean signal=false;
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       if(++twinkleTimes>7){
                           return;
                       }
                        Button[] wordButtons=mSelectedWordView.getButtons();
                        for (int i = 0; i < wordButtons.length; i++) {
                            wordButtons[i].setTextColor(
                                    signal ? Color.RED : Color.WHITE);
                        }
                        signal=!signal;
                    }
                });
            }
        };
        Timer timer=new Timer();
        timer.schedule(task,1,150);
    }

    @Override
    public void onSelectedWordClick(View v) {
        Log.i("tag","delete ");
        Button[] buttons=mSelectedWordView.getButtons();
        for(int i=0;i<buttons.length;i++){
            if(v==buttons[i]){
                if(mSelectedWordView.getState(i)) {
                    //set word gone
                    buttons[i].setText("");
                    //set button state to unuse state
                    mSelectedWordView.setState(i, false);

                    //show hidden Textview
                    int position=mSelectedWordView.getMemento(i);
                    /*View view=mWordsView.getAdapter().getView(position, null, null);
                    view.setVisibility(View.VISIBLE);*/

                    View view=mWordsView.getChildAt(position);
                    TextView textView=(TextView) view.findViewById(R.id.gridview_item_button);
                    textView.setVisibility(View.VISIBLE);
                    //init memento
                    mSelectedWordView.setMemento(i, -1);
                }
            }
        }
    }

    private boolean checkAnswer(){
        int[] selectedAnswer=mSelectedWordView.getMemento();
        for(int i=0;i<answer.length;i++){
            if(answer[i]!=selectedAnswer[i]){
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        Util.saveData(this,mCurrentLevel, mCurrentCoins);
    }

}
